<template>
  <div style="width: 40%;height: 100%;padding-left: 30%;font-size: 16px" >
    <div class="parent-div" style="width: 100%">
    </div>
    <div style="position: fixed;top: 40%;right: 10%">
      <div>QQ群名称：chatgpt交流群</div>
      <div>QQ群   号：701013038</div>
    </div>
    <div style="width: 40%;position: fixed;bottom: 1%;margin: 0 auto;justify-items:center;align-items:center;text-align: center">
      <el-form style="width: 100%" >
        <el-input style="width: 95%" class="input" v-model="text" type="text" placeholder="Type your message here...">
          <template #append><el-button style="width:5%" @click="sendMessage" class="submit" type="primary">发送</el-button></template>
        </el-input>

      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts" name="chat">
import {ref} from "vue";
import {getSnowflakeId} from "@/components/util/snow";

const text = ref<String>("")

const userId = getSnowflakeId()
const sendMessage = () => {
  socket.value.webSocket?.send(text.value)
}
const addDiv = (message) => {
  const newDiv = document.createElement('div');
  newDiv.innerHTML = message;
  document.querySelector('.parent-div').appendChild(newDiv);
};
interface stateInt {
  data: Object
  webSocket: WebSocket | null
}

const socket = ref<stateInt>({
  //推送消息
  data: {},
  webSocket: null,
})

//websocket初始化
const initWebsocket = function () {
  socket.value.webSocket = new WebSocket(
      // 此处填写你要连接的ws地址
      'ws://127.0.0.1:9050/websocket/0', [userId]
  )
  let timer: any
  //建立连接
  socket.value.webSocket.onopen = function () {
    console.log("连接成功")
    /*
     * 连接成功
     * */
    // 发送心跳防止ws协议自动断联
    timer = setInterval(() => {
      // @ts-ignore
      socket.value.webSocket?.send('1')
    }, 1000 * 60)
  }
  //接收服务端消息
  socket.value.webSocket.onmessage = function (e: any) {
    console.log("接收服务端消息")
    /*
     * 收到消息时回调函数
     * */
    // 如果数据对象为字符串，可转换为对象格式
    if (e.data == "关闭") {
      socket.value.webSocket?.close()
      if (timer) {
        clearInterval(timer);
      }
      return;
    }
    addDiv(e.data)
  }
  socket.value.webSocket.onerror = function () {
    console.log("通信异常")
    /*
     * 通讯异常
     * */
    if (timer) {
      clearInterval(timer);
    }
  }
  socket.value.webSocket.close = function () {
    console.log("关闭通信")
    /*
     * 关闭连接时回调函数
     * */
    if (timer) {
      clearInterval(timer);
    }
  }
}


const init = () => {
  initWebsocket()
}
init();
//接收服务端消息
</script>

<style scoped>
.parent-div{
  margin-top: 20px;
}
/* 新蓝风格 新蓝风格 新蓝风格 新蓝风格 新蓝风格 新蓝风格 新蓝风格 新蓝风格 新蓝风格*/
</style>
